import React, { Component, Fragment } from 'react';
import {connect} from 'react-redux';


const TodoList = (props) => {
    const { inputValue, list, changeInputValue, handleClick, handleDelete } = props;
    return (
        <Fragment>
            <div>
                <input
                    value={inputValue}
                    onChange={changeInputValue}
                ></input>
                <button
                    onClick={handleClick}
                >提交</button>
            </div>
            <ul>
                {list.map((item,index) => {
                    return <li onClick={handleDelete} key={index}>{ item }</li>
                })}
            </ul>
        </Fragment>
    )
}

// 让 TodoList 和 store 做连接，中间有个映射关系
// 通过 mapStateToProps 来映射
const mapStateToProps = (state) => {
    return {
        inputValue: state.inputValue,
        list:state.list
    }
}

// 如果我想对store里面的数据做更改，也可以通过store.dispatch来更改
// 这里的函数名的意思： store.dispatch方法挂载到props上
const mapDispatchToProps = (dispatch) => {
    return {
        changeInputValue(e) {
            const action = {
                type: 'change_input_value',
                value: e.target.value
            }
            dispatch(action);
        },

        handleClick() {
            const action = {
                type:'add_item'
            }
            dispatch(action);
        },

        handleDelete(index) {
            const action = {
                type: 'delete_item',
                index
            }
            dispatch(action);
        }

    }
}

export default connect(mapStateToProps,mapDispatchToProps)(TodoList);